package com.demo.test.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HexTcpServer {
    public static void main(String[] args) throws IOException {
        int port = 12345; // 选择一个端口号
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Listening on port: " + port);

        while (true) { // 持续监听连接
            Socket socket = serverSocket.accept(); // 接收连接
            System.out.println("New connection accepted.");

            InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024]; // 缓冲区大小
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) > 0) { // 循环读取数据，直到没有更多数据可读
                if (bytesRead > 0) {
                    byte[] data = new byte[bytesRead];
                    System.arraycopy(buffer, 0, data, 0, bytesRead);
                    String hexString = bytesToHex(data);
                    System.out.println("Received hex data: " + hexString);
                }
            }

            inputStream.close();
            socket.close();
            System.out.println("Connection closed.");
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}